package com.star.spring.netty.server;

import com.star.spring.netty.util.HexUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Device connected: {}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String hexMessage = (String) msg;
        logger.info("Received hex message from device {}: {}", ctx.channel().remoteAddress(), hexMessage);
        
        // Parse the hex data packet
        String parsedData = HexUtils.parseHexPacket(hexMessage);
        logger.info("Parsed hex data:\n{}", parsedData);
        
        // Convert hex to bytes for further processing
        byte[] bytes = HexUtils.hexToBytes(hexMessage);
        logger.debug("Hex message as bytes: {}", bytes);
        
        // In a real implementation, you would process the message according to your protocol
        // and potentially send a response
        ctx.writeAndFlush("ACK");
        
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Exception in channel with device {}", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Device disconnected: {}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }
}